package com.yaodian100.ec.jd;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import com.google.gdata.util.common.base.StringUtil;
import com.jd.ac.sdk.api.DefaultJdClient;
import com.jd.ac.sdk.api.JdClient;
import com.jd.ac.sdk.api.JdException;
import com.jd.ac.sdk.api.request.delivery.DeliveryLogisticsGetRequest;
import com.jd.ac.sdk.api.request.order.OrderGetRequest;
import com.jd.ac.sdk.api.request.order.OrderSearchOfflineRequest;
import com.jd.ac.sdk.api.request.order.OrderSearchOnlineRequest;
import com.jd.ac.sdk.api.request.ware.WareStateUpdateRequest;
import com.jd.ac.sdk.api.response.delivery.DeliveryLogisticsGetResponse;
import com.jd.ac.sdk.api.response.delivery.LogisticsCompany;
import com.jd.ac.sdk.api.response.order.OrderDetail;
import com.jd.ac.sdk.api.response.order.OrderGetResponse;
import com.jd.ac.sdk.api.response.order.OrderSearchOfflineResponse;
import com.jd.ac.sdk.api.response.order.OrderSearchOnlineResponse;
import com.jd.ac.sdk.api.response.order.OrderDetail.Order;
import com.jd.ac.sdk.api.response.order.OrderDetail.Ware;
import com.jd.ac.sdk.api.response.order.OrderResult.ItemInfo;
import com.jd.ac.sdk.api.response.order.OrderResult.OrderInfo;
import com.jd.ac.sdk.api.response.ware.WareStateUpdateResponse;
import com.yaodian100.core.admin.entity.User;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.entity.SimplePager;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.JspUtil;
import com.yaodian100.core.common.utils.StringUtils;
import com.yaodian100.core.logger.service.LogService;
import com.yaodian100.core.mail.entity.Mail;
import com.yaodian100.core.mail.service.MailService;
import com.yaodian100.core.menu.service.MenuService;
import com.yaodian100.core.sms.service.SmsService;
import com.yaodian100.crm.activities.entity.PromotionOuter;
import com.yaodian100.crm.activities.entity.PromotionPresent;
import com.yaodian100.ec.common.EcConstant;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.order.entity.OrderProduct;
import com.yaodian100.ec.order.entity.OrderProductDetail;
import com.yaodian100.ec.order.entity.Orders;
import com.yaodian100.ec.order.service.OrderService;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.entity.Specification;
import com.yaodian100.ec.product.service.Product2Service;
import com.yaodian100.ec.supplierapply.entity.SupplierApply;
import com.yaodian100.ec.supplierapply.service.SupplierApplyService;
import com.yaodian100.ec.tmall.entity.AddrMapping;
import com.yaodian100.ec.tmall.service.impl.TmallServiceImpl;

public class JDSerivceImpl implements JDSerivce {
	@Autowired
	private MemberService memberService;
	@Autowired
	private MenuService menuService;
	@Autowired
	private OrderService orderService;
	private final Logger logger = LoggerFactory.getLogger(TmallServiceImpl.class);
	@Autowired
	private LogService logService;
	@Autowired
	private Product2Service productService;
	@Resource
	private BaseManager baseMgr;
	@Autowired
	private SupplierApplyService supplierApplyService;
	@Resource
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private MailService mailService;
	@Autowired
	private SmsService smsService;
	// private List<JDGiftActivities> jdGiftActivities;
	// private List<JDGiftActivitiesValue> jdGiftValuelist;
	private SimplePager pager;

	// 测试
	// private static final String id = "20901";
	// private static final String key = "AE57C95A758D56F264F2309F8CF35306";
	// private static final String url = "http://220.231.59.70/routerjson";

	// 正式
	private String id = "14446";
	private String key = "A7287FACE5714CC213BA12E2CA13E2EC";
	private static final String url = "http://gw.shop.360buy.com/routerjson";
	private String jdMemberOptionKey = "360buy_member";

	@SuppressWarnings( { "rawtypes", "unchecked" })
	@Override
	public Integer findBuyTimeJDOrderNew(String startDate, String endDate, String OrderState, String Page, String PageSize)
			throws JdException {
		Map<String, Object> jdValues = getJDOrderList(startDate, endDate, OrderState, Page, PageSize);
		Integer totalResult = (Integer) jdValues.get("totalResult");
		List<OrderInfo> orderList = (List<OrderInfo>) jdValues.get("orderList");
		if (orderList != null) {
			for (OrderInfo orderInfo : orderList) {
				// 避免中断订单下载
				if (orderInfo != null) {
					logger.info("outerId:" + orderInfo.getOrderId() + ";orderStartTime:" + orderInfo.getOrderStartTime()
							+ ";endTime:" + orderInfo.getOrderEndTime());
					try {

						DateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						Date payDate = f.parse(orderInfo.getOrderStartTime());
						boolean isNeedDownload = isPaymentDateNeedDownload(payDate);
						if (isNeedDownload) {
							Orders orders = orderInfoToOrders(orderInfo);
							// list.add(orders);
						}
						// System.out.println("---orderStartTime:" + orderInfo.getOrderStartTime());
					} catch (Exception e) {
						logger.error("checkPoint:download order failed! outerOrderId:" + orderInfo.getOrderId());
						e.printStackTrace();
						smsService.sendSms("18621771250", "京东订单下载失败:" + orderInfo.getOrderId(), "");
						// throw new JdException(e);
					}
				}
			}
		}

		return totalResult;
	}

	public Map<String, Object> getJDOrderList(String startDate, String endDate, String OrderState, String Page,
			String PageSize) throws JdException {
		String OptionalFields = "vender_id,order_id,pay_type,order_total_price,freight_price,seller_discount,order_payment,delivery_type,order_state,order_state_remark,invoice_info,order_remark,order_start_time,order_end_time,consignee_info,item_info_list";
		JdClient client = new DefaultJdClient(url, id, key);
		OrderSearchOfflineRequest request = new OrderSearchOfflineRequest();
		Date now = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (startDate == null) {
			Date theStartDate = DateUtils.addMinutes(now, -12);
			request.setStartDate(sdf.format(theStartDate));
		} else {
			request.setStartDate(startDate);
		}
		if (endDate == null) {
			request.setEndDate(sdf.format(now));
		} else {
			request.setEndDate(endDate);
		}
		if (!"".equals(OrderState) && OrderState != null) {
			request.setOrderState(OrderState);// WAIT_SELLER_STOCK_OUT
		}
		request.setPage(Page);// 1
		request.setPageSize(PageSize);// 10
		if (!"".equals(OptionalFields) && OptionalFields != null) {
			request.setOptionalFields(OptionalFields);// vender_id,order_id,pay_type
		}
		OrderSearchOfflineResponse response = client.execute(request);
		logger.debug("startDate:" + request.getStartDate() + "; endDate:" + request.getEndDate());
		Map<String, Object> values = new HashMap<String, Object>();
		values.put("totalResult", Integer.valueOf(response.getOrderInfoResult().getOrderTotal()));
		values.put("orderList", response.getOrderInfoResult().getOrderInfoList());
		return values;
	}

	private void processAddrProblem(String domainSrc, String province, String city, String area, String fullAddress,
			Orders order) {
		Object obj = JspUtil.getAddrByOuterAddrMap(domainSrc, province, city, area);
		AddrMapping am = null;
		if (obj != null) {
			am = (AddrMapping) obj;
			order.setReceiverProvince(am.getYdProvince());
			order.setReceiverCity(am.getYdCity());
			order.setReceiverArea(am.getYdDistrict());
		} else {
			// 若找不到对应，存入EC_ADDR_MAPPING_TMP，日後再行補資料，不设为人工改单
			// order.setReceiverProvince(orderInfo.getConsigneeInfo().getProvince());
			// order.setReceiverCity(orderInfo.getConsigneeInfo().getCity());
			// order.setReceiverArea(orderInfo.getConsigneeInfo().getCounty());
			if (fullAddress == null || fullAddress.length() > 100 || (province == null || province.equals(" "))) {
				String mailTemplate = "京东订单 outOrderId:" + order.getOuterOrderId() + "地址栏位过长或无省市区信息";
				Mail mail = new Mail("京东订单地址栏位过长或无省市区信息", mailTemplate, "andy.chuang@yaodian100.com", "");
				mailService.sendMail(mail);
				fullAddress = "京东地址长度过长，请手动修正！";
				order.setOrderSt("05");
			} else {
				String sql = "insert into EC_ADDR_MAPPING_TMP(OUT_PROVINCE, OUT_CITY, OUT_DISTRICT, OUT_ADDR, DOMAIN_SRC) values(?,?,?,?,?)";
				jdbcTemplate.update(sql, province, city, area, fullAddress, domainSrc);
			}
			if (area != null && area.length() > 0) {
				area = StringUtil.split(area, "(")[0];
				area = StringUtil.split(area, "（")[0];
			}
			String addr = fullAddress.replace(province, "");
			addr = addr.replace(city, "");
			addr = addr.replace(area, "");
			if (area == null || area.length() == 0) {
				// 若区资讯不存在
				area = city;
			}
			if (province.indexOf("省") > 0) {
				order.setReceiverProvince(province.replace("省", ""));
			} else if (province.indexOf("内蒙古自治区") > -1) {
				order.setReceiverProvince(province.replace("自治区", ""));
			} else if (province.indexOf("广西壮族自治区") > -1) {
				order.setReceiverProvince(province.replace("壮族自治区", ""));
			} else if (province.indexOf("西藏自治区") > -1) {
				order.setReceiverProvince(province.replace("自治区", ""));
			} else if (province.indexOf("宁夏回族自治区") > -1) {
				order.setReceiverProvince(province.replace("回族自治区", ""));
			} else if (province.indexOf("新疆维吾尔自治区") > -1) {
				order.setReceiverProvince(province.replace("维吾尔自治区", ""));
			} else {
				order.setReceiverProvince(province);
			}
			order.setReceiverCity(city);
			order.setReceiverArea(area);

			order.setReceiverAddr(addr);
			if ("北京".equals(province)) {
				order.setReceiverCity(province + "市");// 市
				order.setReceiverArea(city);// 区或县
			} else if ("上海".equals(province)) {
				order.setReceiverCity(province + "市");// 市
				order.setReceiverArea(city);// 区或县
			} else {

				order.setReceiverCity(city);// 市
				order.setReceiverArea(area);// 区或县

			}

		}
		// order.setReceiverProvince(orderInfo.getConsigneeInfo().getProvince());// 省
		//
		// if ("北京".equals(orderInfo.getConsigneeInfo().getProvince())) {
		// order.setReceiverCity(orderInfo.getConsigneeInfo().getProvince() + "市");// 市
		// order.setReceiverArea(orderInfo.getConsigneeInfo().getCity());// 区或县
		// } else if ("上海".equals(orderInfo.getConsigneeInfo().getProvince())) {
		// order.setReceiverCity(orderInfo.getConsigneeInfo().getProvince() + "市");// 市
		// order.setReceiverArea(orderInfo.getConsigneeInfo().getCity());// 区或县
		// } else {
		//
		// order.setReceiverCity(orderInfo.getConsigneeInfo().getCity());// 市
		// String area = orderInfo.getConsigneeInfo().getCounty();
		// String areaSplit[] = StringUtil.split(area, "(");
		// if (areaSplit.length > 0) {
		// area = areaSplit[0];
		// }
		// order.setReceiverArea(area);// 区或县
		//
		// }
		// 再检查一次
		// String province = orderInfo.getConsigneeInfo().getProvince();
		// String city = orderInfo.getConsigneeInfo().getCity();
		// String area = orderInfo.getConsigneeInfo().getCounty();
		// String addr = orderInfo.getConsigneeInfo().getFullAddress().replace(province, "");
		// addr = addr.replace(city, "");
		// addr = addr.replace(area, "");
		order.setReceiverAddr(fullAddress);// 地址
		order.setReceiverZip(" ");// 邮编
		if (order.getReceiverProvince() == null || order.getReceiverProvince().length() == 0
				|| order.getReceiverCity() == null || order.getReceiverCity().length() == 0 || order.getReceiverArea() == null
				|| order.getReceiverArea().length() == 0 || order.getReceiverAddr() == null
				|| order.getReceiverAddr().length() == 0 || order.getReceiverZip() == null
				|| order.getReceiverZip().length() == 0 || order.getReceiverProvince().indexOf("台湾") >= 0
				|| order.getReceiverProvince().indexOf("香港") >= 0 || order.getReceiverProvince().indexOf("澳门") >= 0
				|| order.getReceiverProvince().indexOf("钓鱼岛") >= 0) {
			// 直接設成人工改單
			order.setOrderSt("05");
		}
	}

	/**
	 * 批量保存京东订单
	 * 
	 * @param orderInfo
	 * @return
	 */
	@Transactional(readOnly = false)
	private Orders orderInfoToOrders(OrderInfo orderInfo) {

		Orders order = null;
		try {
			boolean isExist = checkOrderExist(orderInfo);// 检查订单是否已建立
			Member member = memberService.get(menuService.get("SystemValue").getOptions().get(jdMemberOptionKey).getMemo1());// dev:0000017112
			// 正式：0000856527
			/* 加入资料库重覆订单检核 */
			try {
				jdbcTemplate.update("insert into ec_order_outer values (?, ?)", member.getDomainSrc(), orderInfo.getOrderId());
				isExist = false;
			} catch (Exception e) {
				logger.info("outerOrderId:" + orderInfo.getOrderId() + " has downloaded already");
				isExist = true;
			}

			if (!isExist) {

				order = new Orders();

				/* 写入order default资料 */
				order.setPaymentTp("50");// 网上支付
				order.setDomainSrc(member.getDomainSrc());
				order.setChannel_child("");
				order.setClientIp("127.0.0.1");
				Date dead1 = DateUtil.getTodayAddDays(1).getTime();
				order.setDeadline(DateUtil.getLastTimestamp(Calendar.HOUR_OF_DAY, dead1));// 网上支付付款期限24hr
				order.setAllowSplit("N");// 拆单
				order.setCodFee(BigDecimal.ZERO);
				if (orderInfo.getOrderRemark() != null && orderInfo.getOrderRemark().length() > 0) {
					// 不改单
					order.setOrderSt("20");
				} else {
					order.setOrderSt("20");
				}
				order.setPaymentSt("10");
				order.setOrderType("3");// 外部商城訂單
				order.setPaymentSrc("08");
				DateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				// order.setPaymentDt(f.parse(orderInfo.getOrderStartTime()));// 付款时间
				// 以下载时间为订单付款时间
				order.setPaymentDt(new Date());
				order.setCash(BigDecimal.ZERO);

				order.setDiscount(new BigDecimal(orderInfo.getSellerDiscount()));// 折扣

				// 应收帐款
				BigDecimal orderReceiverAmount = BigDecimal.ZERO;
				if (orderInfo.getFreightPrice() != null) {

					order.setShipfare(new BigDecimal(orderInfo.getFreightPrice())); // 运费
				} else {
					order.setShipfare(BigDecimal.ZERO);
				}
				if (orderInfo.getOrderTotalPrice() != null) {

					order.setTotalPrice(new BigDecimal(orderInfo.getOrderTotalPrice()));// 总价
					orderReceiverAmount = order.getTotalPrice().subtract(order.getDiscount());
				} else {
					order.setTotalPrice(BigDecimal.ZERO);
				}
				if (orderInfo.getOrderPayment() != null) {

					// order.setCash(new BigDecimal(orderInfo.getOrderPayment()));// 现金
					order.setCash(orderReceiverAmount);
				} else {
					order.setCash(BigDecimal.ZERO);
				}
				// order.setMustPay(new BigDecimal(orderInfo.getOrderPayment()));// 需支付金额
				order.setMustPay(orderReceiverAmount);
				// order.setAmount(new BigDecimal(orderInfo.getOrderPayment()).subtract(BigDecimal.ZERO));// 现金-运费
				order.setAmount(orderReceiverAmount.subtract(order.getShipfare()));// 应收－运费
				order.setInvoiceTp("01");// 发票
				order.setInvoiceTitle(orderInfo.getInvoiceInfo());// 发票头
				order.setOuterOrderId(orderInfo.getOrderId());// 出货单ID
				/*
				 * 处理地址问题
				 */
				processAddrProblem(member.getDomainSrc(), orderInfo.getConsigneeInfo().getProvince(), orderInfo
						.getConsigneeInfo().getCity(), orderInfo.getConsigneeInfo().getCounty(), orderInfo.getConsigneeInfo()
						.getFullAddress(), order);

				order.setReceiverPhone(orderInfo.getConsigneeInfo().getTelephone());// 电话
				order.setReceiverPhoneArea(" ");// 电话区号
				order.setReceiverExt(" ");// 分机
				String receiverMobile = " ";
				if (orderInfo.getConsigneeInfo().getMobile() != null) {
					receiverMobile = orderInfo.getConsigneeInfo().getMobile().trim();
				}
				order.setReceiverMobile(receiverMobile);// 手机
				order.setReceiverEmail(" ");// email
				order.setMemo(orderInfo.getOrderRemark());// 备忘录
				order.setMemberId(member.getMemberId());// 用户ID
				order.setLoginId(member.getLoginId());// 登录ID

				order.setJoinMustPay(new BigDecimal(orderInfo.getOrderPayment()));// 需支付金额
				// channel:yaodian100?
				order.setChannel("yaodian100");
				order.setMemberName(member.getName());// 用户名
				if (order.getMemberName() == null) {
					order.setMemberName("360buyUser");
				}
				order.setOrderDt(f.parse(orderInfo.getOrderStartTime()));// 创建时间
				order.setReceiverEmail(" ");// 收货人email
				order.setReceiverName(orderInfo.getConsigneeInfo().getFullname());// 收货人姓名
				// order.setSyncDt(f.parse(orderInfo.getOrderStartTime()));// 付款时间
				// TODO:直接同步後台
				order.setSyncDt(DateUtil.incrementMinutes(-60).getTime());
				orderService.save(order);

				Specification spec = null;
				Product product = null;
				int i = 1;

				if (orderInfo != null && orderInfo.getItemInfoList() != null) {
					// BigDecimal agio = BigDecimal.ZERO;
					List<OrderProduct> orderProductList = new ArrayList<OrderProduct>();
					for (ItemInfo itemInfo : orderInfo.getItemInfoList()) {
						if (itemInfo != null) {
							String outerSpecId = itemInfo.getOuterSkuId();

							if ("".equals(outerSpecId) && outerSpecId.length() <= 0) {
								// 若没有outerSpecId
								order.setOrderSt("05");
								String mailTemplate = "京东订单 outOrderId:" + order.getOuterOrderId() + " 商品规格未设定, outerSkuId: "
										+ itemInfo.getSkuId();

								Mail mail = new Mail("京东商品商家规格未设定", mailTemplate, "andy.chuang@yaodian100.com",
										"joy.sheng@yaodian100.com");
								mailService.sendMail(mail);
							} else {
								spec = productService.getSpecification(Long.parseLong(outerSpecId));
								product = productService.get(spec.getProductId());
								if (orderInfo.getItemInfoList().size() > i) {
									addOrderProducts(itemInfo.getSkuName(), itemInfo.getSkuId(), itemInfo.getItemTotal(), itemInfo
											.getJdPrice(), order, product, spec, i, 0, orderProductList);

								} else {
									addOrderProducts(itemInfo.getSkuName(), itemInfo.getSkuId(), itemInfo.getItemTotal(), itemInfo
											.getJdPrice(), order, product, spec, i, 1, orderProductList);
								}
								i++;
							}

						}
					}

				}
				// Long giftSpecId = getGift(order.getPaymentDt(), order.getAmount());
				List<Map<String, Long>> sMapList = getGift(order.getPaymentDt(), order.getAmount(), member.getDomainSrc());
				if (sMapList != null) {
					for (int j = 0; j < sMapList.size(); j++) {

						add360buyGift(order, i, sMapList.get(j).get("giftSpecId"));

						i += sMapList.size();
					}
				}
				// if (giftSpecId != null) {
				// add360buyGift(order, i, giftSpecId);
				// i++;
				// }
				add360buyShipingCard(order, i, orderInfo.getOrderId());
				// 更新订单的joinorders
				order.setJoinOrders(order.getOrderId());
				// TODO:赠品赠送，以待审核处理，晚上再检查
				// order.setOrderSt("00");
				orderService.update(order);
				// 12／19上
				// orderService.calcOrderProduct(order);
				// orderService.calcOrderCash(order);
				// orderService.update(order);
				Orders calcOrder = orderService.getOrder(order.getOrderId());
				calcOrder = orderService.calcOrderProduct(calcOrder);
				calcOrder = orderService.calcOrderCash(calcOrder);
				orderService.update(calcOrder);
				logService.save(this.getClass().getName(), "createOrderWithPay", new Object[] { order });
			}
		} catch (Exception e) {
			logger.error("trade to order fail, orderInfo:" + orderInfo.getOrderId(), e);
			throw new RuntimeException(e);
		}
		return order;
	}

	public static void main(String[] args) {
		int total = 10;
		for (int i = 0; i < 100; i++) {
			int random = (int) (Math.random() * total + 1);
			System.out.println("random:" + random);
		}
	}

	@Override
	public String testGift(Date orderDate, BigDecimal price, String domainSrc) throws ParseException {
		List<Map<String, Long>> sMapList = getGift(orderDate, price, domainSrc);
		for (int i = 0; i < sMapList.size(); i++) {
			System.out.println(sMapList.get(i).get("giftSpecId"));
			Long psecId = sMapList.get(i).get("giftSpecId");
			Specification spec = (Specification) baseMgr.get(Specification.class, psecId);
			System.out.println(spec.getProductId());

		}
		return null;
	}

	/**
	 * 赠品送出标示加一
	 * 
	 * @return
	 */
	// private String addGiftAfnjQty(Map<String, Object> giftMap) {
	// jdGiftValueService.updateGiftAfnjQty(giftMap);
	// return null;
	//
	// }

	/**
	 * @param orderDate
	 * @return specId
	 * @throws ParseException
	 */
	@Transactional(readOnly = false)
	private List<Map<String, Long>> getGift(Date orderDate, BigDecimal price, String domainSrc) throws ParseException {
		Map<String, Long> specIdMap = null;
		List<Map<String, Long>> mapList = null;
		DetachedCriteria dc = DetachedCriteria.forClass(PromotionOuter.class);
		dc.add(Restrictions.eq("domainSrc", domainSrc));
		dc.add(Restrictions.le("startDate", orderDate));
		dc.add(Restrictions.ge("endDate", orderDate));
		dc.add(Restrictions.le("price", price));
		dc.add(Restrictions.eq("status", "1"));
		Object[] result = baseMgr.findByCriteria(dc);
		if (result != null && result.length > 0) {
			PromotionOuter jdPromotion = (PromotionOuter) result[0];
			Object[] values = baseMgr.queryByHql("from PromotionPresent where prId=? and qty - afnjQty > 0",
					new Object[] { jdPromotion.getId() });
			if (values == null || values.length == 0) {
				return null;
			} else {
				if (values.length == 1) {
					specIdMap = new HashMap<String, Long>();
					mapList = new ArrayList<Map<String, Long>>();
					PromotionPresent jv = (PromotionPresent) values[0];
					jv.setAfnjQty(jv.getAfnjQty() + 1);
					baseMgr.update(jv);
					specIdMap.put("giftSpecId", jv.getSpecId());
					mapList.add(specIdMap);
					return mapList;
					// return jv.getSpecId();
				} else {
					if ("1".equals(jdPromotion.getSendWay())) {
						specIdMap = new HashMap<String, Long>();
						mapList = new ArrayList<Map<String, Long>>();
						int random = (int) (Math.random() * values.length);
						PromotionPresent jv = (PromotionPresent) values[random];
						jv.setAfnjQty(jv.getAfnjQty() + 1);
						baseMgr.update(jv);
						specIdMap.put("giftSpecId", jv.getSpecId());
						mapList.add(specIdMap);
						return mapList;
						// return jv.getSpecId();
					} else {
						mapList = new ArrayList<Map<String, Long>>();
						for (int i = 0; i < values.length; i++) {
							specIdMap = new HashMap<String, Long>();
							PromotionPresent jv = (PromotionPresent) values[i];
							jv.setAfnjQty(jv.getAfnjQty() + 1);
							baseMgr.update(jv);
							specIdMap.put("giftSpecId", jv.getSpecId());
							mapList.add(specIdMap);
						}
						return mapList;
					}
				}
			}
		} else {
			return null;
		}
	}

	/**
	 * 检查订单是否存在
	 * 
	 * @param trade
	 * @return
	 */
	public Orders checkOrderExists(OrderInfo orderInfo) {
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("outerOrderId", orderInfo.getOrderId());
		List<Orders> existOrders = orderService.getList(0, 1, crit, null);
		if (null != existOrders && existOrders.size() > 0) {
			logger.error("trade tid is exist :" + orderInfo.getOrderId());
			return existOrders.get(0);
		} else {
			return null;
		}
	}

	OrderProduct add360buyGift(Orders order, int i, Long psecId) {
		OrderProduct entityProd = new OrderProduct();
		Specification spec = (Specification) baseMgr.get(Specification.class, psecId);
		Product product = (Product) baseMgr.get(Product.class, spec.getProductId());
		entityProd.setCategoryPath(product.getMainCategoryPath());
		entityProd.setEcCost(product.getProductCost());
		entityProd.setPmId(product.getPmID());
		entityProd.setProdId(product.getProductId());
		entityProd.setProdName(product.getProductName());
		entityProd.setProdSeq(i);
		entityProd.setProdSpecId(spec.getSpecificationId().toString());
		entityProd.setProdSpecName(spec.getSpecificationName());
		entityProd.setProdTp(Product.PRODUCT_TYPE.PRESENT.getValue());
		entityProd.setQty(1);
		entityProd.setUnitPrice(BigDecimal.ZERO);
		entityProd.setTotalPrice(BigDecimal.ZERO);
		entityProd.setDiscount(BigDecimal.ZERO);
		entityProd.setReturnRule(product.getReturnRule());
		entityProd.setOrder(order);
		entityProd.setOrderId(order.getOrderId());
		User user = (User) baseMgr.get(User.class, product.getPmID());
		entityProd.setPmGroup(user.getGroupName());
		orderService.saveOrderProd(entityProd);
		addOrderProductDetail(null, order, entityProd, product);
		return entityProd;
	}

	OrderProduct add360buyShipingCard(Orders order, int i, String outerOrderId) {
		OrderProduct entityProd = new OrderProduct();
		Product product = productService.get(menuService.get("SystemValue").getOptions().get("360buy_shipingCard_pid")
				.getMemo1());
		Specification spec = product.getSpecifications().get(0);
		entityProd.setCategoryPath(product.getMainCategoryPath());
		entityProd.setEcCost(product.getProductCost());
		entityProd.setPmId(product.getPmID());
		entityProd.setProdId(product.getProductId());
		entityProd.setProdName("京东商城出货单(订单编号:" + outerOrderId + ")");
		entityProd.setProdSeq(i);
		entityProd.setProdSpecId(spec.getSpecificationId().toString());
		entityProd.setProdSpecName(spec.getSpecificationName());
		entityProd.setProdTp(String.valueOf(product.getProductType()));
		entityProd.setQty(1);
		entityProd.setUnitPrice(BigDecimal.ZERO);
		entityProd.setTotalPrice(BigDecimal.ZERO);
		entityProd.setDiscount(BigDecimal.ZERO);
		entityProd.setReturnRule(product.getReturnRule());
		entityProd.setOrder(order);
		entityProd.setOrderId(order.getOrderId());
		User user = (User) baseMgr.get(User.class, product.getPmID());
		entityProd.setPmGroup(user.getGroupName());
		orderService.saveOrderProd(entityProd);
		addOrderProductDetail(null, order, entityProd, product);
		return entityProd;
	}

	/**
	 * 新增订单商品
	 * 
	 * @param tmallOrder
	 * @param order
	 * @param product
	 * @param spec
	 * @param i
	 * @return
	 */
	private OrderProduct addOrderProducts(String skuName, String skuId, String itemTotal, String jdPrice, Orders order,
			Product product, Specification spec, int i, int j, List<OrderProduct> orderProductList) {
		OrderProduct entityProd = new OrderProduct();
		// // 加入外部商品号
		// entityProd.setOuterProdId(itemInfo.getSkuId());
		entityProd.setCategoryPath(product.getMainCategoryPath());
		entityProd.setEcCost(product.getProductCost());
		entityProd.setPmId(product.getPmID());
		entityProd.setProdId(product.getProductId());
		entityProd.setProdName(skuName);
		entityProd.setProdSeq(i);
		entityProd.setProdSpecId(spec.getSpecificationId().toString());
		entityProd.setProdSpecName(skuId);
		if (entityProd.getProdSpecName() == null) {
			entityProd.setProdSpecName(" ");
		}
		// entityProd.setProdTp(String.valueOf(product.getProductType()));
		entityProd.setProdTp(Product.PRODUCT_TYPE.MAIN.getValue());
		entityProd.setQty(Integer.parseInt(itemTotal));
		entityProd.setUnitPrice(new BigDecimal(jdPrice));
		// 因amount＝totalPrice-coupon-discount
		// entityProd.setTotalPrice(new BigDecimal(tmallOrder.getTotalFee()).setScale(1, BigDecimal.ROUND_HALF_DOWN));
		entityProd.setTotalPrice(entityProd.getUnitPrice().multiply(BigDecimal.valueOf(entityProd.getQty())));
		BigDecimal orderDiscount = order.getDiscount();// 订单总折扣
		if (j != 1) {
			// entityProd.setDiscount((orderDiscount.divide(order.getTotalPrice())).multiply(entityProd.getTotalPrice()));
			BigDecimal productDiscount = (entityProd.getTotalPrice().divide(order.getTotalPrice(), 2,
					BigDecimal.ROUND_HALF_DOWN)).multiply(orderDiscount).setScale(2, BigDecimal.ROUND_DOWN);
			entityProd.setDiscount(productDiscount);
		} else {
			BigDecimal sumProductDiscount = BigDecimal.ZERO;
			for (OrderProduct op : orderProductList) {
				sumProductDiscount = sumProductDiscount.add(op.getDiscount());
			}
			entityProd.setDiscount(orderDiscount.subtract(sumProductDiscount));// 折扣
		}
		orderProductList.add(entityProd);
		entityProd.setReturnRule(product.getReturnRule());
		entityProd.setOrder(order);
		entityProd.setOrderId(order.getOrderId());
		User user = (User) baseMgr.get(User.class, product.getPmID());
		entityProd.setPmGroup(user.getGroupName());
		orderService.saveOrderProd(entityProd);
		addOrderProductDetail(skuId, order, entityProd, product);
		return entityProd;
	}

	// private OrderProduct addOrderProducts(Ware ware, Orders order, Product product, Specification spec, int i) {
	// OrderProduct entityProd = new OrderProduct();
	// entityProd.setCategoryPath(product.getMainCategoryPath());
	// entityProd.setEcCost(product.getProductCost());
	// entityProd.setPmId(product.getPmID());
	// entityProd.setProdId(product.getProductId());
	// entityProd.setProdName(ware.getSkuId());
	// entityProd.setProdSeq(i);
	// entityProd.setProdSpecId(spec.getSpecificationId().toString());
	// entityProd.setProdSpecName(ware.getWareName());
	// if (entityProd.getProdSpecName() == null) {
	// entityProd.setProdSpecName(" ");
	// }
	// entityProd.setProdTp(String.valueOf(product.getProductType()));
	// entityProd.setQty(Integer.parseInt(ware.getWareTotal()));
	// entityProd.setUnitPrice(new BigDecimal(ware.getJdPrice()));
	// // 因amount＝totalPrice-coupon-discount
	// // entityProd.setTotalPrice(new BigDecimal(tmallOrder.getTotalFee()).setScale(1, BigDecimal.ROUND_HALF_DOWN));
	// entityProd.setTotalPrice(entityProd.getUnitPrice().multiply(BigDecimal.valueOf(entityProd.getQty())));
	// entityProd.setDiscount(BigDecimal.ZERO);
	// entityProd.setReturnRule(product.getReturnRule());
	// entityProd.setOrder(order);
	// entityProd.setOrderId(order.getOrderId());
	// User user = (User) baseMgr.get(User.class, product.getPmID());
	// entityProd.setPmGroup(user.getGroupName());
	// orderService.saveOrderProd(entityProd);
	// // TODO
	// addOrderProductDetail(null, order, entityProd, product);
	// return entityProd;
	// }

	/**
	 * 新增订单商品明细
	 * 
	 * @param order
	 * @param entityProd
	 * @param product
	 * @return
	 */
	private OrderProductDetail addOrderProductDetail(String skuId, Orders order, OrderProduct entityProd, Product product) {
		OrderProductDetail entityDetail = new OrderProductDetail();
		if (skuId != null) {
			// 外部productId, skuId
			// entityDetail.setOuterProdId(outerProdId);
			entityDetail.setOuterSkuId(skuId);
		}
		entityDetail.setAmount(entityProd.getUnitPrice().multiply(BigDecimal.valueOf(entityProd.getQty())));
		entityDetail.setDetailSeq(entityProd.getProdSeq());
		entityDetail.setDetailTp(entityProd.getProdTp());
		entityDetail.setEcCost(entityProd.getEcCost());
		entityDetail.setProdId(entityProd.getProdId());
		entityDetail.setProdName(entityProd.getProdName());
		entityDetail.setProdSeq(entityProd.getProdSeq());
		entityDetail.setProdSpecId(entityProd.getProdSpecId());
		entityDetail.setProdSpecName(entityProd.getProdSpecName());
		entityDetail.setQty(entityProd.getQty());
		entityDetail.setReturnRule(entityProd.getReturnRule());
		entityDetail.setUnitPrice(entityProd.getUnitPrice());
		entityDetail.setUnitVolumeWeight(product.getProductVolume());
		entityDetail.setUnitWeight(product.getProductWeight());
		if (StringUtils.isBlank(product.getCanUseCod())) {
			entityDetail.setCanUseCod("Y");
		} else {
			entityDetail.setCanUseCod(product.getCanUseCod());
		}
		if (product.getProductType() == 1 && null != product.getExpectShipDate()) {
			entityDetail.setExpectShipDate(EcConstant.PATTERN_DATE_FORMAT.format(product.getExpectShipDate()));
		}
		if (product.getProductType() != 1) {
			// BO/订制商品供备货时间
			// 轉單商品
			SupplierApply sp = supplierApplyService.get(product.getSupplierId());
			if (StringUtils.equals(product.getIsScm(), "Y")) {
				// 有訂制天數
				if (StringUtils.equals(product.getUseDeliveryDay(), "Y")) {
					entityDetail.setDeliveryDay(product.getDeliveryDay());
				}
			}
			// BO商品
			if (StringUtils.equals(product.getIsScm(), "B")) {
				// 有訂制天數
				if (StringUtils.equals(product.getUseDeliveryDay(), "Y")) {
					entityDetail.setDeliveryDay(product.getDeliveryDay());
				} else {
					if (null != sp && null != sp.getBoToWHDate()) {
						entityDetail.setBoToWhDate(sp.getBoToWHDate());
					}
				}
			}
		}
		entityDetail.setVendId(product.getSupplierId());
		entityDetail.setOrderProd(entityProd);
		entityDetail.setOrderId(order.getOrderId());
		entityDetail.setOrderProdId(entityProd.getOrderProdId());
		entityDetail.setOrder(order);
		orderService.saveOrderDetail(entityDetail);
		return entityDetail;
	}

	// @Override
	// public Orders findBuyOrderIdOrderInfo(String orderId) throws JdException {
	// JdClient client = new DefaultJdClient(url, id, key);
	// String optionalFields =
	// "vender_id,order_id,pay_type,order_total_price,freight_price,seller_discount,order_payment,delivery_type,order_state,order_state_remark,invoice_info,order_remark,order_start_time,order_end_time,consignee_info,item_info_list";
	// OrderGetRequest request = new OrderGetRequest();
	// Orders result = null;
	// request.setOrderId(orderId);
	// request.setOptionalFields(optionalFields);
	// OrderGetResponse response = client.execute(request);
	// if (response != null && "".equals(response)) {
	// for (Order order : response.getOrderDetail().getOrders()) {
	// if (order != null) {
	// result = orderInfoToOrder(order);
	// }
	// }
	// }
	// return result;
	//
	// }

	// /**
	// * 下载订单
	// *
	// * @param order
	// * @return
	// */
	// public Orders orderInfoToOrder(Order orderInfo) {
	// Orders order = null;
	// try {
	// boolean isExist = checkOrderExist(orderInfo);// 检查订单是否已建立
	//
	// if (!isExist) {
	// Member member = memberService.get(menuService.get("SystemValue").getOptions().get("360buy_member").getMemo1());//
	// 0000017112
	// order = new Orders();
	// /* 写入order default资料 */
	// order.setPaymentTp("50");// 网上支付
	// order.setDomainSrc(member.getDomainSrc());
	// order.setChannel_child("");
	// order.setClientIp("127.0.0.1");
	// Date dead1 = DateUtil.getTodayAddDays(1).getTime();
	// order.setDeadline(DateUtil.getLastTimestamp(Calendar.HOUR_OF_DAY, dead1));// 网上支付付款期限24hr
	// order.setAllowSplit("N");
	// order.setCodFee(BigDecimal.ZERO);
	// order.setOrderSt("00");
	// order.setPaymentSt("10");
	// order.setOrderType("3");// 外部商城訂單
	// order.setPaymentSrc("08");
	// DateFormat f = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");
	// order.setPaymentDt(f.parse(orderInfo.getOrderStartTime()));// 付款时间
	// order.setCash(BigDecimal.ZERO);
	//
	// order.setDiscount(new BigDecimal(orderInfo.getTotalDiscountFee()));// 折扣
	// if (orderInfo.getFreightPrice() != null) {
	//
	// order.setShipfare(new BigDecimal(orderInfo.getFreightPrice())); // 运费
	// } else {
	// order.setShipfare(BigDecimal.ZERO);
	// }
	// if (orderInfo.getOrderTotalPrice() != null) {
	//
	// order.setTotalPrice(new BigDecimal(orderInfo.getOrderTotalPrice()));// 总价
	// } else {
	// order.setTotalPrice(BigDecimal.ZERO);
	// }
	// if (orderInfo.getPayment() != null) {
	//
	// order.setCash(new BigDecimal(orderInfo.getPayment()));// 现金
	// } else {
	// order.setCash(BigDecimal.ZERO);
	// }
	// order.setMustPay(new BigDecimal(orderInfo.getPayment()));// 需支付金额
	// // order
	// // .setAmount(new BigDecimal(orderInfo.getOrderPayment()).subtract(new
	// // BigDecimal(orderInfo.getFreightPrice())));// 现金-运费
	// order.setAmount(new BigDecimal(orderInfo.getPayment()).subtract(BigDecimal.ZERO));// 现金-运费
	// order.setInvoiceTp("01");// 发票
	// order.setInvoiceTitle(orderInfo.getInvoiceInfo());// 发票头
	// order.setReceiverProvince(" ");// 省
	//
	// order.setReceiverCity("");// 市
	// order.setReceiverArea("");// 区或县
	//
	// order.setReceiverAddr(orderInfo.getConsigneeInfo().getUserAddress());// 地址
	// order.setReceiverZip(" ");// 邮编
	// order.setReceiverPhone(orderInfo.getConsigneeInfo().getUserTelephone());// 电话
	// order.setReceiverPhoneArea(" ");// 电话区号
	// order.setReceiverExt(" ");// 分机
	// order.setReceiverMobile(orderInfo.getConsigneeInfo().getUserMobilephone());// 手机
	// order.setReceiverEmail(" ");// email
	// order.setMemo(orderInfo.getBuyerOrderRemark());// 备忘录
	// order.setMemberId(member.getMemberId());// 用户ID
	// order.setLoginId(member.getLoginId());// 登录ID
	// order.setOuterOrderId(orderInfo.getOrderId());// 出货单ID
	// order.setJoinMustPay(new BigDecimal(orderInfo.getPayment()));// 需支付金额
	// // channel:yaodian100?
	// order.setChannel("yaodian100");
	// order.setMemberName(member.getName());// 用户名
	// if (order.getMemberName() == null) {
	// order.setMemberName("360buyUser");
	// }
	// order.setOrderDt(f.parse(orderInfo.getOrderStartTime()));// 创建时间
	// order.setReceiverEmail(" ");// 收货人email
	// order.setReceiverName(orderInfo.getConsigneeInfo().getUserName());// 收货人姓名
	// order.setSyncDt(f.parse(orderInfo.getOrderStartTime()));// 付款时间
	//
	// orderService.save(order);
	//
	// Specification spec = null;
	// Product product = null;
	// int i = 1;
	//
	// if (orderInfo != null && orderInfo.getWareInfos() != null) {
	// for (Ware ware : orderInfo.getWareInfos()) {
	// if (ware != null) {
	// String outerSpecId = ware.getSkuOutId();
	// if (outerSpecId == null) {
	//
	// outerSpecId = "00003471";// 内部商品DI
	// }
	//
	// spec = productService.getSpecification(Long.parseLong(outerSpecId));
	// product = productService.get(spec.getProductId());
	// addOrderProducts(ware, order, product, spec, i);
	// i++;
	//
	// }
	// }
	// }
	//
	// System.out.println("orderInfo:" + orderInfo);
	//
	// // 更新订单的joinorders
	// order.setJoinOrders(order.getOrderId());
	// orderService.update(order);
	// logService.save(this.getClass().getName(), "createOrderWithPay", new Object[] { order });
	// }
	// } catch (Exception e) {
	// logger.error("trade to order fail, orderInfo:" + orderInfo.getOrderId(), e);
	// }
	// return order;
	//
	// }

	/**
	 * 新增订单商品
	 * 
	 * @param tmallOrder
	 * @param order
	 * @param product
	 * @param spec
	 * @param i
	 * @return
	 */
	// private OrderProduct addOrderProduct(Ware tmallOrder, Orders order, Product product, Specification spec, int i) {
	//
	// OrderProduct entityProd = new OrderProduct();
	// entityProd.setCategoryPath(product.getMainCategoryPath());
	// entityProd.setEcCost(product.getProductCost());
	// entityProd.setPmId(product.getPmID());
	// entityProd.setProdId(product.getProductId());
	// entityProd.setProdName(tmallOrder.getWareId());
	// entityProd.setProdSeq(i);
	// entityProd.setProdSpecId(spec.getSpecificationId().toString());
	// entityProd.setProdSpecName(tmallOrder.getWareName());
	// if (entityProd.getProdSpecName() == null) {
	// entityProd.setProdSpecName(" ");
	// }
	// entityProd.setProdTp(String.valueOf(product.getProductType()));
	// entityProd.setQty(Integer.parseInt(tmallOrder.getWareTotal()));
	// entityProd.setUnitPrice(new BigDecimal(tmallOrder.getJdPrice()));
	// // 因amount＝totalPrice-coupon-discount
	// // entityProd.setTotalPrice(new BigDecimal(tmallOrder.getTotalFee()).setScale(1, BigDecimal.ROUND_HALF_DOWN));
	// entityProd.setTotalPrice(entityProd.getUnitPrice().multiply(BigDecimal.valueOf(entityProd.getQty())));
	// entityProd.setDiscount(new BigDecimal(tmallOrder.getWareDiscountFee()));
	// entityProd.setReturnRule(product.getReturnRule());
	// entityProd.setOrder(order);
	// entityProd.setOrderId(order.getOrderId());
	// User user = (User) baseMgr.get(User.class, product.getPmID());
	// entityProd.setPmGroup(user.getGroupName());
	// orderService.saveOrderProd(entityProd);
	// addOrderProductDetail(null, order, entityProd, product);
	// return entityProd;
	//
	// }

	/**
	 * 检查订单是否存在
	 * 
	 * @param trade
	 * @return
	 */
	public boolean checkOrderExist(Order orderInfo) {
		long count = baseMgr.countByHql("from Orders where outerOrderId=?", new Object[] { orderInfo.getOrderId() });
		if (count > 0) {
			return true;
		}
		return false;
	}

	/**
	 * 检查订单是否存在
	 * 
	 * @param trade
	 * @return
	 */
	public boolean checkOrderExist(OrderInfo orderInfo) {
		long count = baseMgr.countByHql("from Orders where outerOrderId=?", new Object[] { orderInfo.getOrderId() });
		if (count > 0) {
			logger.debug("orderExist, outerId:" + orderInfo.getOrderId());
			return true;
		}
		return false;
	}

	@Override
	public List<LogisticsCompany> getJDLogistics() throws JdException {
		JdClient client = new DefaultJdClient(url, id, key);
		DeliveryLogisticsGetRequest request = new DeliveryLogisticsGetRequest();
		DeliveryLogisticsGetResponse response = client.execute(request);
		List<LogisticsCompany> logisticslist = new ArrayList<LogisticsCompany>();
		if (response != null) {
			for (LogisticsCompany ac : response.getLogisticsCompanies().getLogisticsList()) {
				if (ac != null) {
					logisticslist.add(ac);
				}
			}

		}

		return logisticslist;
	}

	@Override
	public String changeWareState(String wareId, String wareState, String tradeNo) throws JdException {
		JdClient client = new DefaultJdClient(url, id, key);
		WareStateUpdateRequest req = new WareStateUpdateRequest();
		req.setTradeNo(tradeNo);
		req.setWareId(wareId);
		// req.setWareState(WareStateUpdateRequest.STATE_OFF_SHELF);
		req.setWareState(wareState);
		WareStateUpdateResponse rsp = client.execute(req);
		if (rsp != null) {
			rsp.getCode();// 若==0 成功

		}
		return null;
	}

	/**
	 * 生成20位的流水号
	 * 
	 * @return
	 */
	public String getUID20() {
		StringBuffer sb = new StringBuffer();
		// 4位年份+2位月份+2位日期+2位小时+2位分钟+2位秒数+6位流水号或6位随机数
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		sb.append(formatter.format(new Date())).append(getRandomStr(6));

		return sb.toString();
	}

	/**
	 * 根据传入位数，生成数字随机数
	 * 
	 * @return length
	 */
	private static String getRandomStr(int length) {
		synchronized (JDSerivceImpl.class) {
			return RandomStringUtils.randomNumeric(length);
		}
	}

	// 检查是否应下载订单：预设付款后一小时下载
	private boolean isPaymentDateNeedDownload(Date paymentDate) {
		// 没有反悔时间
		return true;
		// Calendar checkDate = Calendar.getInstance();
		// checkDate.add(Calendar.HOUR_OF_DAY, -1);
		// if (checkDate.getTime().after(paymentDate)) {
		// // 若检查时间晚于付款时间
		// return true;
		//
		// }
		//
		// return false;
	}

	@Override
	public String findProductId(String id) throws JdException {
		JdClient client = new DefaultJdClient(url, id, key);
		OrderSearchOnlineRequest request = new OrderSearchOnlineRequest();
		request.setStartDate("2011-04-27 12:12:23");
		request.setEndDate("2011-05-26 23:23:33");
		request.setOrderState("WAIT_SELLER_STOCK_OUT");
		request.setPage("1");
		request.setPageSize("10");
		request.setOptionalFields("vender_id,freight_price,pay_type");
		OrderSearchOnlineResponse response = client.execute(request);
		return null;
	}

	@Override
	public void getJDOrder(String[] orderIds) {
		JdClient client = new DefaultJdClient(url, id, key);
		for (String orderId : orderIds) {
			OrderGetRequest request = new OrderGetRequest();
			request.setOrderId(orderId);
			request
					.setOptionalFields("vender_id,freight_price,pay_type,fact_freight_price,total_discount_fee,payment,seller_order_remark,order_end_time,delivery_date_remark,ware_total_price,order_total_price,order_state,invoice_info,buyer_order_remark,order_start_time,ware_id,sku_out_id,ware_out_id,sku_id,product_no,gift_point,ware_name,jd_price,ware_discount_fee,ware_total,consignee_info");
			try {
				OrderGetResponse response = client.execute(request);
				OrderDetail od = response.getOrderDetail();

				for (Order order : od.getOrders()) {
					System.out.println("orderState:" + order.getOrderState());
					System.out.println("orderStartTime:" + order.getOrderStartTime());
					// System.out.println("orderId:" + order.getOrderId());
					this.orderDetailToOrders(order);
				}
			} catch (JdException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	public OrderDetail getJDOrderNoSave(String orderId) throws Exception {
		JdClient client = new DefaultJdClient(url, id, key);
		OrderGetRequest request = new OrderGetRequest();
		request.setOrderId(orderId);
		request
				.setOptionalFields("vender_id,freight_price,pay_type,fact_freight_price,total_discount_fee,payment,seller_order_remark,order_end_time,delivery_date_remark,ware_total_price,order_total_price,order_state,invoice_info,buyer_order_remark,order_start_time,ware_id,sku_out_id,ware_out_id,sku_id,product_no,gift_point,ware_name,jd_price,ware_discount_fee,ware_total,consignee_info");
		try {
			OrderGetResponse response = client.execute(request);
			OrderDetail od = response.getOrderDetail();
			return od;
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 批量保存京东订单
	 * 
	 * @param orderInfo
	 * @return
	 */
	@Transactional(readOnly = false)
	private Orders orderDetailToOrders(Order orderInfo) {

		Orders order = null;
		try {
			boolean isExist = checkOrderExist(orderInfo);// 检查订单是否已建立
			Member member = memberService.get(menuService.get("SystemValue").getOptions().get(jdMemberOptionKey).getMemo1());// dev:0000017112
			/* 加入资料库重覆订单检核 */
			try {
				jdbcTemplate.update("insert into ec_order_outer values (?, ?)", member.getDomainSrc(), orderInfo.getOrderId());
				isExist = false;
			} catch (Exception e) {
				logger.info("outerOrderId:" + orderInfo.getOrderId() + " has downloaded already!");
				isExist = true;
			}
			if (!isExist) {
				// 正式：0000856527
				order = new Orders();
				/* 写入order default资料 */
				order.setPaymentTp("50");// 网上支付
				order.setDomainSrc(member.getDomainSrc());
				order.setChannel_child("");
				order.setClientIp("127.0.0.1");
				Date dead1 = DateUtil.getTodayAddDays(1).getTime();
				order.setDeadline(DateUtil.getLastTimestamp(Calendar.HOUR_OF_DAY, dead1));// 网上支付付款期限24hr
				order.setAllowSplit("N");// 拆单
				order.setCodFee(BigDecimal.ZERO);
				if (orderInfo.getBuyerOrderRemark() != null && orderInfo.getBuyerOrderRemark().length() > 0) {
					// 不改单
					order.setOrderSt("05");
				} else {
					order.setOrderSt("05");
				}
				order.setPaymentSt("10");
				order.setOrderType("3");// 外部商城訂單
				order.setPaymentSrc("08");
				DateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				order.setPaymentDt(f.parse(orderInfo.getOrderStartTime()));// 付款时间
				order.setCash(BigDecimal.ZERO);
				// TODO:没有卖家discount!?
				order.setDiscount(new BigDecimal(orderInfo.getTotalDiscountFee()));// 折扣

				// 应收帐款
				BigDecimal orderReceiverAmount = BigDecimal.ZERO;
				if (orderInfo.getFreightPrice() != null) {

					order.setShipfare(new BigDecimal(orderInfo.getFreightPrice())); // 运费
				} else {
					order.setShipfare(BigDecimal.ZERO);
				}
				if (orderInfo.getOrderTotalPrice() != null) {

					order.setTotalPrice(new BigDecimal(orderInfo.getOrderTotalPrice()));// 总价
					orderReceiverAmount = order.getTotalPrice().subtract(order.getDiscount());
				} else {
					order.setTotalPrice(BigDecimal.ZERO);
				}
				if (orderInfo.getPayment() != null) {

					// order.setCash(new BigDecimal(orderInfo.getOrderPayment()));// 现金
					order.setCash(orderReceiverAmount);
				} else {
					order.setCash(BigDecimal.ZERO);
				}
				// order.setMustPay(new BigDecimal(orderInfo.getOrderPayment()));// 需支付金额
				order.setMustPay(orderReceiverAmount);
				// order.setAmount(new BigDecimal(orderInfo.getOrderPayment()).subtract(BigDecimal.ZERO));// 现金-运费
				order.setAmount(orderReceiverAmount.subtract(order.getShipfare()));// 应收－运费
				order.setInvoiceTp("01");// 发票
				order.setInvoiceTitle(orderInfo.getInvoiceInfo());// 发票头

				order.setOuterOrderId(orderInfo.getOrderId());// 出货单ID
				/*
				 * 处理地址问题
				 */
				processAddrProblem(member.getDomainSrc(), " ", " ", " ", orderInfo.getConsigneeInfo().getUserAddress(), order);

				order.setReceiverPhone(orderInfo.getConsigneeInfo().getUserTelephone());// 电话
				order.setReceiverPhoneArea(" ");// 电话区号
				order.setReceiverExt(" ");// 分机
				String receiverMobile = " ";
				if (orderInfo.getConsigneeInfo().getUserMobilephone() != null) {
					receiverMobile = orderInfo.getConsigneeInfo().getUserMobilephone().trim();
				}
				order.setReceiverMobile(receiverMobile);// 手机
				order.setReceiverEmail(" ");// email
				order.setMemo(orderInfo.getBuyerOrderRemark());// 备忘录
				order.setMemberId(member.getMemberId());// 用户ID
				order.setLoginId(member.getLoginId());// 登录ID
				order.setJoinMustPay(new BigDecimal(orderInfo.getPayment()));// 需支付金额
				// channel:yaodian100?
				order.setChannel("yaodian100");
				order.setMemberName(member.getName());// 用户名
				if (order.getMemberName() == null) {
					order.setMemberName("360buyUser");
				}
				order.setOrderDt(f.parse(orderInfo.getOrderStartTime()));// 创建时间
				order.setReceiverEmail(" ");// 收货人email
				order.setReceiverName(orderInfo.getConsigneeInfo().getUserName());// 收货人姓名
				// order.setSyncDt(f.parse(orderInfo.getOrderStartTime()));// 付款时间
				// TODO:直接同步後台
				order.setSyncDt(DateUtil.incrementMinutes(-60).getTime());
				orderService.save(order);

				Specification spec = null;
				Product product = null;
				int i = 1;

				if (orderInfo != null && orderInfo.getWareInfos() != null) {
					// BigDecimal agio = BigDecimal.ZERO;
					List<OrderProduct> orderProductList = new ArrayList<OrderProduct>();
					for (Ware itemInfo : orderInfo.getWareInfos()) {
						if (itemInfo != null) {
							String outerSpecId = itemInfo.getSkuOutId();

							if ("".equals(outerSpecId) && outerSpecId.length() <= 0) {
								// 若没有outerSpecId
								order.setOrderSt("05");
								String mailTemplate = "京东订单 outOrderId:" + order.getOuterOrderId() + " 商品规格未设定, outerSkuId: "
										+ itemInfo.getSkuId();

								mailService.sendMail("andy.chuang@yaodian100.com", "joy.sheng@yaodian100.com", null, "京东商品商家规格未设定",
										mailTemplate, null, null, "andy.chuang@yaodian100.com");
							} else {
								spec = productService.getSpecification(Long.parseLong(outerSpecId));
								product = productService.get(spec.getProductId());
								if (orderInfo.getWareInfos().size() > i) {
									addOrderProducts(itemInfo.getWareName(), itemInfo.getSkuId(), itemInfo.getWareTotal(), itemInfo
											.getJdPrice(), order, product, spec, i, 0, orderProductList);

								} else {
									addOrderProducts(itemInfo.getWareName(), itemInfo.getSkuId(), itemInfo.getWareTotal(), itemInfo
											.getJdPrice(), order, product, spec, i, 1, orderProductList);
								}
								i++;
							}

						}
					}
				}
				// Long giftSpecId = getGift(order.getOrderDt(), order.getAmount());
				// if (giftSpecId != null) {
				// add360buyGift(order, i, giftSpecId);
				// i++;
				// }

				List<Map<String, Long>> sMapList = getGift(order.getPaymentDt(), order.getAmount(), member.getDomainSrc());
				if (sMapList != null) {
					for (int j = 0; j < sMapList.size(); j++) {

						add360buyGift(order, i, sMapList.get(j).get("giftSpecId"));

						i += sMapList.size();
					}
				}

				add360buyShipingCard(order, i, orderInfo.getOrderId());
				// 更新订单的joinorders
				order.setJoinOrders(order.getOrderId());
				// TODO:設成人工改單，避免出錯
				order.setOrderSt("05");
				orderService.update(order);
				// 12／19上
				// orderService.calcOrderProduct(order);
				// orderService.calcOrderCash(order);
				// orderService.update(order);
				Orders calcOrder = orderService.getOrder(order.getOrderId());
				calcOrder = orderService.calcOrderProduct(calcOrder);
				calcOrder = orderService.calcOrderCash(calcOrder);
				orderService.update(calcOrder);
				logService.save(this.getClass().getName(), "createOrderWithPay", new Object[] { order });
			}
		} catch (Exception e) {
			logger.error("trade to order fail, orderInfo:" + orderInfo.getOrderId(), e);
			throw new RuntimeException(e);
		}
		return order;
	}

	@Override
	public void testGetJDOrder(String startDate, String endDate, String orderId, String orderState, String page,
			String pageSize) throws JdException {
		JdClient client = new DefaultJdClient(url, id, key);
		OrderSearchOfflineRequest request = new OrderSearchOfflineRequest();

		Date now = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (startDate == null) {
			Date theStartDate = DateUtils.addMinutes(now, -12);
			request.setStartDate(sdf.format(theStartDate));
		} else {
			request.setStartDate(startDate);
		}
		if (endDate == null) {
			request.setEndDate(sdf.format(now));
		} else {
			request.setEndDate(endDate);
		}
		if (!"".equals(orderState) && orderState != null) {
			request.setOrderState(orderState);// WAIT_SELLER_STOCK_OUT
		}
		request.setPage(page);// 1
		request.setPageSize(pageSize);// 10
		String OptionalFields = "vender_id,order_id,pay_type,order_total_price,freight_price,seller_discount,order_payment,delivery_type,order_state,order_state_remark,invoice_info,order_remark,order_start_time,order_end_time,consignee_info,item_info_list";
		request.setOptionalFields(OptionalFields);
		OrderSearchOfflineResponse response = client.execute(request);

		if (response != null) {
			for (OrderInfo orderInfo : response.getOrderInfoResult().getOrderInfoList()) {
				if (orderId.equals(orderInfo.getOrderId())) {
					System.out.println("county:" + orderInfo.getConsigneeInfo().getCounty());
				}
			}
		}
	}

	// public List<JDGiftActivities> getJdGiftActivities() {
	// return jdGiftActivities;
	// }
	//
	// public void setJdGiftActivities(List<JDGiftActivities> jdGiftActivities) {
	// this.jdGiftActivities = jdGiftActivities;
	// }

	public SimplePager getPager() {
		return pager;
	}

	public void setPager(SimplePager pager) {
		this.pager = pager;
	}

	/**
	 * @return the id
	 */
	public String getId() {
		return id;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(String id) {
		this.id = id;
	}

	/**
	 * @return the key
	 */
	public String getKey() {
		return key;
	}

	/**
	 * @param key the key to set
	 */
	public void setKey(String key) {
		this.key = key;
	}

	/**
	 * @return the jdMemberOptionKey
	 */
	public String getJdMemberOptionKey() {
		return jdMemberOptionKey;
	}

	/**
	 * @param jdMemberOptionKey the jdMemberOptionKey to set
	 */
	public void setJdMemberOptionKey(String jdMemberOptionKey) {
		this.jdMemberOptionKey = jdMemberOptionKey;
	}

	// public List<JDGiftActivitiesValue> getJdGiftValuelist() {
	// return jdGiftValuelist;
	// }
	//
	// public void setJdGiftValuelist(List<JDGiftActivitiesValue> jdGiftValuelist) {
	// this.jdGiftValuelist = jdGiftValuelist;
	// }

}
